<script setup>
import { onMounted, ref } from "vue";
import luckysheet from "luckysheet";
import LuckyExcel from "luckyexcel";
import dayjs from "dayjs";
import AnalyesAPI from "@/api/system/analyes.ts";
import { useAnalysetStore } from "@/store/index.ts";
import { transformData, getHeaders, splitDataIntoPages } from "@/utils/method";
import CapacityB from "@/components/analysisSheetComponents/ambientAir/tmpl77/index.vue";
import MyDevice from "@/components/analysisSheetComponents/component/MyDevice.vue";
// 复制粘贴
import Index from "@/components/analysisSheetComponents/component/index.vue";
// pdf内容
import indexPdf from "@/components/analysisSheetComponents/ambientAir/tmpl77/indexPdf.vue";
let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: "zh",
  autoCalculate: true,
  data: [
    {
      column: 10, // 列数
      row: 10, // 列数
      defaultRowHeight: 50, // 自定义行高
      defaultColWidth: 100, // 自定义列宽
      celldata: [
        // 初始化表格数据，第一行包含表头
        { r: 0, c: 0, v: "样品唯一性标识" }, // A1
        { r: 1, c: 0, v: "样品编号" }, // A1
        { r: 1, c: 1, v: "类型" }, // A1
        { r: 1, c: 2, v: "滤膜编号" }, // A1
        { r: 0, c: 3, v: "( )采样体积 V(m³)" }, // A1
        { r: 0, c: 4, v: "初重B（ ）" }, // A1
        { r: 1, c: 4, v: "初重1" }, // A1
        { r: 1, c: 5, v: "初重2" }, // A1
        { r: 1, c: 6, v: "初重3" }, // A1
        { r: 1, c: 7, v: "平均值" }, // A1
        { r: 0, c: 8, v: "终重A（ ）" }, // A1
        { r: 1, c: 8, v: "终重1" }, // A1
        { r: 1, c: 9, v: "终重2" }, // A1
        { r: 1, c: 10, v: "终重3" }, // A1
        { r: 1, c: 11, v: "平均值" }, // A1
        { r: 0, c: 12, v: "样品净重m( )" }, // A1
        { r: 0, c: 13, v: "样品浓度C( )" }, // A1
        { r: 0, c: 14, v: "测定结果" }, // A1
        { r: 0, c: 15, v: "备注" }, // A1
      ], // 初始化数据
      config: {
        merge: {
          "0_0": {
            r: 0, // 起始行
            c: 0, // 起始列
            rs: 1, // 跨越的行数
            cs: 3, // 跨越的列数
          },
          "0_3": {
            r: 0, // 起始行
            c: 3, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_4": {
            r: 0, // 起始行
            c: 4, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "0_8": {
            r: 0, // 起始行
            c: 8, // 起始列
            rs: 1, // 跨越的行数
            cs: 4, // 跨越的列数
          },
          "0_12": {
            r: 0, // 起始行
            c: 12, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_13": {
            r: 0, // 起始行
            c: 13, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_14": {
            r: 0, // 起始行
            c: 14, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
          "0_15": {
            r: 0, // 起始行
            c: 15, // 起始列
            rs: 2, // 跨越的行数
            cs: 1, // 跨越的列数
          },
        }, // 合并单元格
        columnlen: {
          // 设置列宽
          0: 130, // 第一列宽度 150px
          1: 130, // 第二列宽度 120px
          2: 130, // 第三列宽度 180px
          3: 130, // 第四列宽度 100px
          4: 100, // 第五列宽度 200px
          5: 100, // 第六列宽度 150px
          6: 100, // 第六列宽度 150px
          7: 100, // 第六列宽度 150px
          8: 100, // 第六列宽度 150px
          9: 100, // 第六列宽度 150px
        }, // 表格列宽
      },
    },
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([{ table: "仪器名称", id: 1 }]);
const switchAB = ref(true);
const waterForm = ref({
  // b_bzlmjc
  bdatas: {
    b_bzlmjc: [
      {
        bzlmbh_0: "",
        yszl_0: "",
        cz1_0: "",
        cz2_0: "",
        pjz_0: "",
        yszlcz_0: "",
        yxcz_0: "",
        sfhg_0: "",
      },
      {
        bzlmbh_1: "",
        yszl_1: "",
        cz1_1: "",
        cz2_1: "",
        pjz_1: "",
        yszlcz_1: "",
        yxcz_1: "",
        sfhg_1: "",
      },
      {
        bzlmbh_2: "",
        yszl_2: "",
        cz1_2: "",
        cz2_2: "",
        pjz_2: "",
        yszlcz_2: "",
        yxcz_2: "",
        sfhg_2: "",
      },
    ],
    b_yparr: [
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
      {
        ypbh: "",
        lvbh: "",
        cytj: "",
        cz1: "",
        cz2: "",
        cz3: "",
        pjz1: "",
        zz1: "",
        zz2: "",
        zz3: "",
        pjz2: "",
        ypjz: "",
        ypnd: "",
        notes: "",
      },
    ],
    b_notes: "",
  },

  // b_bzlmjc: [],
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  },
});
const analyseStatusPage = useAnalysetStore();
const record_sn = analyseStatusPage.waterForm.record_sn;
const processedData = ref([]);
const cdatas = ref([]);
const checkDialogVisible = ref(false);
const checkTime = ref("");
const sheetData = ref("");
const jsonData = ref(null);
const switchAdd = ref(true);
// pdf显示隐藏
const showTargetPage = ref(false);
const tableHeaders = ref([]);
const tabler = ref([]);
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取初始数据并保存在响应式变量中
  sheetData.value = options.data;
  // 获取表单信息
  getWaterCapacity();
  // 复制粘贴
  getMethod();
});
// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number; //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
    ? analyseStatusPage.waterForm.tableItem.test_method
    : analyseStatusPage.waterForm.tableItem.test_method_number; //分析方法
  waterForm.value.category_id =
    analyseStatusPage.waterForm.tableItem.sample_category; // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates;
};

// 点击保存
const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map((row) => {
    return row
      .map((cell) => {
        return cell
          ? {
              field: cell.m || "默认字段",
              value: cell.v || null,
            }
          : null;
      })
      .filter((cell) => cell !== null); // 删除 null 值
  });
  // 调用函数
  processedData.value = processData(data);
  cdatas.value = transformData(processedData.value);

  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status;
    delete waterForm.value.reviewer_id;
  }
  //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    // record_sn: record_sn,
    record_sn: 77,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value,
  }).then((data) => {
    console.log("调接口拿数据", data);
    ElMessage.success("保存成功！");
    // getWaterCapacity();
    switchAdd.value = false;
  });
};

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  AnalyesAPI.getAnalyseACapacity({
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 25,
    record_sn: record_sn,
    // record_sn: 40,
  }).then((data) => {
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data;
      sheetData.value = data.configs;
      options.data = sheetData.value;
      luckysheet.create(options);
      waterForm.value.bdatas =
        Array.isArray(data.bdatas) && data.bdatas.length === 0
          ? {}
          : data.bdatas;
      // b_bzlmjc
      waterForm.value.b_bzlmjc =
        Array.isArray(data.b_bzlmjc) && data.b_bzlmjc.length === 0
          ? {}
          : data.b_bzlmjc;
      processedData.value = data.adatas;
      tableHeaders.value = splitDataIntoPages(data.adatas, 22);
      // tabler.value = getHeaders(data.adatas, 23);
      tabler.value = getHeadersData();
      console.log(tableHeaders.value, "tableHeaders.value");
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      };
    }
  });
};

const getHeadersData = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map((row) => {
    return row
      .map((cell) => {
        return cell
          ? {
              field: cell.m || "默认字段",
              value: cell.v || null,
            }
          : null;
      })
      .filter((cell) => cell !== null); // 删除 null 值
  });
  // 提取表头信息
  const header1 = data[0]
    .map((item) => item.value)
    .filter((value) => value !== null);

  return header1;
};

const processData = (data) => {
  if (!data || data.length < 2) {
    return [];
  }
  // 提取表头信息
  const header1 = data[0]
    .map((item) => item.value)
    .filter((value) => value !== null);

  const header2 = data[1]
    .map((item) => item.value)
    .filter((value) => value !== null);

  // const row = data[2].map(item => item.value);
  const row = data.slice(2).map((rowData) => rowData.map((item) => item.value));
  const resultArray = [];
  for (let i = 0; i < row.length; i++) {
    const currentRow = row[i];
    const result = {
      [header2[0]]: currentRow[0] || null, // 样品编号
      [header2[1]]: currentRow[1] || null, // 类型
      [header2[2]]: currentRow[2] || null, // 滤膜编号
      [header1[1]]: currentRow[3] || null, // 采样体积
      [header2[3]]: currentRow[4] || null, // 初重1
      [header2[4]]: currentRow[5] || null, // 初重2
      [header2[5]]: currentRow[6] || null, // 初重3
      [header2[6]]: currentRow[7] || null, //平均值
      [header2[7]]: currentRow[8] || null, // 终重1
      [header2[8]]: currentRow[9] || null, // 终重2
      [header2[9]]: currentRow[10] || null, // 终重3
      [header2[10] + "0"]: currentRow[11] || null, //平均值
      [header1[4]]: currentRow[12] || null, // 样品净重,
      [header1[5]]: currentRow[13] || null, // 样品浓度,
      [header1[6]]: currentRow[14] || null, // 测定结果
      [header1[7]]: currentRow[15] || null, // 备注
    };

    resultArray.push(result);
  }
  console.log(resultArray, "resultArray");
  return resultArray;
};

const handleSwitch = () => {
  switchAB.value = !switchAB.value;
};

// 下载
const downloadDetail = async () => {
  // console.log("下载");
  showTargetPage.value = true;
  await nextTick();
  window.print();
  setTimeout(() => {
    showTargetPage.value = false;
  }, 1000);
};
</script>

<template>
  <div class="card">
    <div v-show="!showTargetPage && switchAB">
      <el-card class="box-card">
        <h1 style="text-align: center">
          环境空气和废气 颗粒物分析原始记录（A面）
        </h1>
        <div>SXLPHJ/JL/CX-22-77</div>
        <table class="table">
          <tr>
            <td colspan="2" style="width: 10%">任务编号</td>
            <td colspan="3" style="width: 15%">
              <el-input
                v-model="waterForm.task_name"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2" style="width: 10%">采样日期</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.sampling_time"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2" style="width: 10%">分析日期</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.anal_time"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2" style="width: 10%">样品类别</td>
            <td colspan="4">
              <el-input
                v-model="waterForm.category_id"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="2">分析方法</td>
            <td colspan="8">
              <el-input
                v-model="waterForm.method"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">分析项目</td>
            <td colspan="3">
              <el-input
                v-model="waterForm.fxxm"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td style="width: 50%" colspan="2">检出限</td>
            <td colspan="4">
              <el-input
                v-model="waterForm.limit_val"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <MyDevice :water-form="waterForm" :colspan="8" />
          <tr>
            <td colspan="2">第一次称量环境温湿度</td>
            <td colspan="8">
              <el-input
                v-model="waterForm.temperature1"
                style="width: 150px; border: 1px solid transparent"
                placeholder="请输入"
              >
                <template #append>
                  <span style="background-color: transparent; color: black">
                    ℃
                  </span>
                </template>
              </el-input>
              <el-input
                v-model="waterForm.humidity1"
                style="width: 150px; border: 1px solid transparent"
                placeholder="请输入"
              >
                <template #append>
                  <span style="background-color: transparent; color: black">
                    %RH
                  </span>
                </template>
              </el-input>
            </td>
            <td colspan="2">第二次称量环境温湿度</td>
            <td colspan="7">
              <el-input
                v-model="waterForm.temperature2"
                style="width: 150px; border: 1px solid transparent"
                placeholder="请输入"
              >
                <template #append>
                  <span style="background-color: transparent; color: black">
                    ℃
                  </span>
                </template>
              </el-input>
              <el-input
                v-model="waterForm.humidity2"
                style="width: 150px; border: 1px solid transparent"
                placeholder="请输入"
              >
                <template #append>
                  <span style="background-color: transparent; color: black">
                    %RH
                  </span>
                </template>
              </el-input>
            </td>
          </tr>
          <tr>
            <td colspan="2">计算公式</td>
            <td colspan="8">
              <el-input
                v-model="waterForm.js_formula"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">样品处理</td>
            <td colspan="7">
              <el-input
                v-model="waterForm.ypcl"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width: 100%; height: 500px" />
        <table class="table">
          <tr>
            <td style="width: 2%">备注</td>
            <td>
              <el-input
                v-model="waterForm.notes"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
        </table>
        <table class="table">
          <tr>
            <td
              style="width: 10%; font-weight: bold; text-align: center"
              colspan="17"
            >
              标准滤膜检查
            </td>
          </tr>
          <tr>
            <td style="width: 10%" colspan="3">标准滤膜编号</td>
            <td style="width: 10%" colspan="2">原始质量( )</td>
            <td style="width: 10%" colspan="2">称重1( )</td>
            <td style="width: 10%" colspan="2">称重2( )</td>
            <td style="width: 10%" colspan="2">平均值( )</td>
            <td style="width: 10%" colspan="2">与原始质量差值( )</td>
            <td style="width: 10%" colspan="2">允许差值( )</td>
            <td style="width: 10%" colspan="2">是否合格</td>
          </tr>

          <tr v-for="(item, index) in waterForm.bzlmjc" :key="index">
            <td style="width: 10%" colspan="3">
              <el-input
                v-model="item.bz_bzlmbh"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td style="width: 10%" colspan="2">
              <el-input
                v-model="item.bz_yszl"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td style="width: 10%" colspan="2">
              <el-input
                v-model="item.bz_cz1"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td style="width: 10%" colspan="2">
              <el-input
                v-model="item.bz_cz2"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td style="width: 10%" colspan="2">
              <el-input
                v-model="item.bz_pjz"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td style="width: 10%" colspan="2">
              <el-input
                v-model="item.bz_yszlcz"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td style="width: 10%" colspan="2">
              <el-input
                v-model="item.bz_yxcz"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td style="width: 10%" colspan="2">
              <el-input
                v-model="item.bz_sfhg"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td style="width: 10%" colspan="2">备注</td>
            <td colspan="15">
              <el-input
                v-model="waterForm.bnotes"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
        </table>
      </el-card>
    </div>
    <div v-show="showTargetPage">
      <indexPdf
        :waterForm="waterForm"
        :tableHeaders="tableHeaders"
        :tabler="tabler"
      />
    </div>
    <div v-show="!switchAB">
      <capacity-b :water-form="waterForm" />
    </div>
    <!--    底部公共按钮 (复制粘贴)-->
    <div v-show="!showTargetPage">
      <Index
        :water-form="waterForm"
        :handle-add-water-ph="handleAddWaterPh"
        :check-time="checkTime"
        :switch="true"
        :switch-a-b="switchAB"
        :handle-switch="handleSwitch"
        :get-water-capacity="getWaterCapacity"
        :switch-add="switchAdd"
        :download-detail="downloadDetail"
      />
    </div>
  </div>
</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
